#include"../heads/doublelist.h"
#include<stdio.h>
#include<stdlib.h>

LinkDouble creatLinkDouble(){
    LinkDouble list;
    list.head=(DoublyNode*)malloc(sizeof(DoublyNode));
    if (list.head== NULL) {
        fprintf(stderr, "创建链表，无法为链表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    list.head->data=0;
    list.head->prev=NULL;
    list.head->next=NULL;
    list.tail=list.head;
    list.size=1;
    return list;

}

void addToTail(LinkDouble *list,int data){
    if(list->head==NULL){
        fprintf(stderr,"链表为空，无法添加元素");
        return ;
    }
    DoublyNode* newNode= (DoublyNode*)malloc(sizeof(DoublyNode));
    if (newNode == NULL) {
        fprintf(stderr, "添加元素失败，无法为链表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    newNode->data=data;
    newNode->next=list->head->prev;
    newNode->prev=list->tail;
    list->tail->next=newNode;
    list->tail=newNode;
    list->size++;

}

void remove_Element(LinkDouble *list,int data){
    DoublyNode *current=list->head;
    while(current!=NULL && current->data!=data){
        current=current->next;
    }
    if(current==NULL){
        fprintf(stderr,"无该元素");
        return ;

    }
    if(current==list->head){
        list->head=current->next;
        if(list->head!=NULL){
            list->head->prev=NULL;
        }
    }else if(current==list->tail){
        list->tail=current->prev;
        list->tail->next=NULL;
    }else{
        current->prev->next=current->next;
        current->next->prev=current->prev;
    }
    free(current);
    list->size--;

}

void printDouble(LinkDouble *list){
    DoublyNode *current=list->head;
    while(current!=NULL){
        printf("%d<->",current->data);
        current=current->next;
    }
    if(current==NULL)
        printf("NULL");
}

void addToHead(LinkDouble *list,int data){
    DoublyNode *newNode= (DoublyNode*)malloc(sizeof(DoublyNode));
    if (newNode == NULL) {
        fprintf(stderr, "添加元素失败，无法为链表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    if(list->head==NULL){
        list->head=newNode;
        list->tail=newNode;
    }else{
        newNode->next=list->head;
        newNode->data=data;
        newNode->prev=NULL;
        list->head->prev=newNode;
        list->head=newNode;
    }
    list->size++;

}

void changeDoubleList(LinkDouble *list,int originalElement, int newElement){
    DoublyNode *current=list->head;
    while(current->data!=originalElement){
        current=current->next;
    }
    current->data=newElement;
}

void destoryDoubleNode(LinkDouble *list){
    DoublyNode *current=list->head;
    while(current!=NULL){
        DoublyNode *temp=current;

        free(temp);
        current=current->next;
    }
    list->head=NULL;
    list->tail=NULL;
    list->size=0;
}
